package housekeeping.util;

import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * ClassName: RedisUtil
 * Description:
 *
 * @Author 迷藏
 * @Create 2025/7/8 20:35
 * @Version 1.0
 */
@Component
public class RedisUtil {
    private final RedisTemplate<String, Object> redisTemplate;

    public RedisUtil(RedisTemplate<String, Object> redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    /**
     * 存储用户会话信息
     */
    public void saveUserSession(String token, String account, String role) {
        String key = "user";
        Map<String, Object> userInfo = new HashMap<>();
        userInfo.put("account", account);
        userInfo.put("role", role);

        redisTemplate.opsForHash().putAll(key, userInfo);
        // 设置过期时间，例如30分钟
        redisTemplate.expire(key, 30, TimeUnit.MINUTES);
    }

    /**
     * 获取用户会话信息
     */
    public Map<Object, Object> getUserSession(String token) {
        String key = "user";
        return redisTemplate.opsForHash().entries(key);
    }

    /**
     * 获取用户账号
     */
    public String getUserAccount(String token) {
        String key = "user";
        return (String) redisTemplate.opsForHash().get(key, "account");
    }

    /**
     * 获取用户角色
     */
    public String getUserRole(String token) {
        String key = "user";
        return (String) redisTemplate.opsForHash().get(key, "role");
    }

    /**
     * 删除用户会话
     */
    public void deleteUserSession(String token) {
        String key = "user";
        redisTemplate.delete(key);
    }

    /**
     * 刷新会话过期时间
     */
    public void refreshSession(String token) {
        String key = "user";
        redisTemplate.expire(key, 30, TimeUnit.MINUTES);
    }
}
